import { useState, useMemo } from 'react';
import { Modal, Button, Progress, Spin, Input, Upload, Form, Checkbox, message } from 'antd';
import { LoadingOutlined } from '@ant-design/icons';
import { importLanguages, importLanguageProcess } from '../service';
import '../style.less';

let interVal: any = null;

export default function LangImportModal(props: any) {
    const { visible, setVisible, callback } = props;
    const [uploadStep, setUploadStep] = useState(1);
    const [uploading, setUploading] = useState(false);
    const [percent, setPercent] = useState(0);
    const [uploadStatus, setUploadStatus] = useState(false); // 导入状态 true：失败
    const [file, setFile] = useState<any>({});
    const [uploadMessage, setUploadMessage] = useState<string>('');
    const [isDataError, setIsDataError] = useState(false);
    const [isCover, setIsCover] = useState(false);
    const [form] = Form.useForm();

    const handleChange = (e: any) => {
        setIsCover(e.target.checked);
    };

    const textHandleChange = () => {
        setIsCover(!isCover);
    };

    const handleUpload = async () => {
        const formData: any = new FormData();
        formData.append('file', file);
        formData.append('isCover', isCover);
        setUploading(true);
        try {
            const result = await importLanguages(formData);
            setUploading(false);
            setUploadStep(2);
            GetProcessInfo(result);
            interVal = setInterval(() => GetProcessInfo(result), 500);
        } catch (error: any) {
            message.error(error);
            setUploading(false);
        };
    };

    const GetProcessInfo = async (key: any) => {
        let str = `${key.replaceAll('"', '')}`;
        try {
            const result = await importLanguageProcess({ key: str });
            if (!result) return;
            setPercent(result.CurrentProcess);
            setUploadMessage(result.Msg);
            switch (result.State) {
                case 2:
                    message.error('导入失败');
                    setUploadStatus(true);
                    clearInterval(interVal)
                    break;
                case 3:
                    message.error('不知名错误，导入已取消');
                    setUploadStatus(true);
                    clearInterval(interVal)
                case 4:
                    message.success('导入成功');
                    clearInterval(interVal);
                    break;
            };
        } catch (error: any) {
            message.error(error);
        };
    };

    const handleImportOk = () => {
        if (JSON.stringify(file) == '{}') {
            setIsDataError(true);
            form.setFields([{
                name: 'file',
                errors: ['数据导入错误，请重新选择文件']
            }]);
        } else if (!file?.name?.endsWith('.xls') && !file?.name?.endsWith('.xlsx')) {
            form.setFields([{
                name: 'file',
                errors: ['仅支持上传.xls或.xlsx格式文件']
            }]);
        } else {
            handleUpload();
        };
    };

    const onCancel = () => {
        setVisible(false);
    };

    const goBack = () => {
        callback && callback();
        onCancel();
    };

    return (
        <Modal
            title='导入多语言'
            visible={visible}
            onCancel={onCancel}
            width={500}
            className='inbiz-lang-import-modal'
            footer={
                uploadStep == 1
                    ?
                    [
                        <Button key='cancel' onClick={onCancel} type='default'>取消</Button>,
                        <Button loading={uploading} key='ok' type='primary' onClick={handleImportOk}>确定</Button>
                    ]
                    :
                    [
                        <Button key='cancel' onClick={goBack} type='default'>取消</Button>,
                        <Button type='primary' onClick={goBack}>确定</Button>
                    ]
            }
        >
            {
                uploadStep == 1 ? (
                    <>
                        <Form
                            name='langImport'
                            layout='vertical'
                            form={form}
                        >
                            <Form.Item
                                label='多语言数据'
                                name='file'
                                help={
                                    isDataError
                                        ? '数据导入错误，请重新选择文件'
                                        : '仅支持上传.xls或.xlsx格式文件'
                                }
                                rules={[
                                    { required: true, message: '请上传多语言文件' },
                                    () => ({
                                        validator(_, value) {
                                            if (file) {
                                                const FileExt = file?.name?.replace(/.+\./, '');
                                                try {
                                                    if (!['xls', 'xlsx'].includes(FileExt)) {
                                                        return Promise.reject(new Error('文件格式错误'));
                                                    }
                                                    return Promise.resolve();
                                                } catch (err: any) {
                                                    return Promise.reject(new Error(err));
                                                }
                                            } else {
                                                setIsDataError(true);
                                                return Promise.reject(new Error('数据导入错误，请重新选择文件'));
                                            }
                                        },
                                    }),
                                ]}
                            >
                                <Input value={file?.name} disabled status={isDataError ? 'error' : ''} />
                                <Upload
                                    name='file'
                                    accept='.xls,.xlsx'
                                    showUploadList={false}
                                    multiple={false}
                                    beforeUpload={(file) => {
                                        form.setFieldValue('file', file);
                                        setFile(file);
                                        return false;
                                    }}
                                >
                                    <Button
                                        type='primary'
                                        onClick={() => setIsDataError(false)}
                                    >
                                        选择文件
                                    </Button>
                                </Upload>
                            </Form.Item>
                        </Form>
                        <div className='inbiz-lang-import-modal-ifCover'>
                            <div onClick={textHandleChange}>是否覆盖</div>
                            <Checkbox onChange={handleChange} checked={isCover} />
                            <div onClick={textHandleChange}>注：勾选此项将会覆盖已有多语言</div>
                        </div>
                    </>
                ) : (
                    <>
                        <p style={{ marginBottom: 8 }}>{uploadStatus ? '导入失败：' : percent == 100 ? '导入成功：' : '正在导入：'}{file?.name}</p>
                        <Progress
                            percent={percent}
                            status={uploadStatus ? 'exception' : percent == 100 ? 'success' : 'normal'}
                        />
                        <div style={{ marginTop: 8, height: 60 }} className='inbiz-lang-import-modal-spinning'>
                            {uploadMessage}&nbsp;&nbsp;
                            {percent != 100 && !uploadStatus && <Spin size={'small'} indicator={<LoadingOutlined />} />}
                        </div>
                    </>
                )
            }
        </Modal >
    )
}